package com.cunjiankang.ui;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.*;
import com.android.volley.*;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cunjiankang.R;
import com.cunjiankang.adapter.QueryResultAdapter;
import com.cunjiankang.bean.request.BaseRequest;
import com.cunjiankang.bean.request.QueryRequest;
import com.cunjiankang.bean.response.BaseResponse;
import com.cunjiankang.bean.response.QueryResultResponse;
import com.cunjiankang.bean.response.ResultDetailResponse;
import com.cunjiankang.bean.vo.QueryResult;
import com.cunjiankang.util.Contants;
import com.cunjiankang.util.HttpUtil;
import com.cunjiankang.util.PreferenceUtil;
import com.cunjiankang.util.TextViewUtil;
import com.cunjiankang.view.CustomProgressDialog;
import com.google.gson.Gson;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @ClassName: MedicineQueryActivity
 * @Description:
 * @author liyongqiang
 * @date 2015-3-5 下午11:40:13
 * 
 */
public class MedicineQueryActivity extends BaseActivity {

	@BindView(id = R.id.btn_back, click = true)
	private Button btnBack;
	@BindView(id = R.id.btn_query, click = true)
	private Button btnQuery;
	@BindView(id = R.id.edit_content, click = true)
	private EditText editContent;
	@BindView(id = R.id.result_list)
	private ListView resultList;
	@BindView(id = R.id.layout_query_type)
	private View layoutQueryType;
	@BindView(id = R.id.layout_content)
	private View layoutContent;
	@BindView(id = R.id.layout_tip_content)
	private View layoutTip;
	@BindView(id = R.id.tv_drug_desc)
	private TextView tvDrugDesc;
	@BindView(id = R.id.img_close, click = true)
	private ImageView imgClose;
	@BindView(id = R.id.no_data)
	private View nodata;
	@BindView(id = R.id.tv_info)
	private TextView tvInfo;

	@BindView(id = R.id.haolingju_logo, click = true)
	private ImageView haolingjuImageView;

	private RequestQueue mRequestQueue;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_medicine_query);
		mRequestQueue = Volley.newRequestQueue(this);
		super.setRootView();
	}

	@Override
	public void initWidget() {
		super.initWidget();
		String username = PreferenceUtil.readString(this,
				Contants.SP.username);
		TextViewUtil textViewUtil = new TextViewUtil();
		String info = String.format(getString(R.string.welcome_info),
				username);
		int start = info.indexOf(username);
		int end = start + username.length();
		tvInfo.setText(textViewUtil.getForegroundColorSpan(
				this, info, start, end,
				"#e95013"));
		resultList.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Contants.starTime = System.currentTimeMillis();
				return false;
			}
		});
		String userGroupId = PreferenceUtil.readString(this, Contants.SP.local_grubid);
		if (userGroupId.equals("259") || userGroupId.equals("260") || userGroupId.equals("261")) {
			haolingjuImageView.setVisibility(View.VISIBLE);
		} else {
			haolingjuImageView.setVisibility(View.GONE);
		}
	}

	@Override
	public void widgetClick(View view) {
		super.widgetClick(view);
		Contants.starTime = System.currentTimeMillis();
		switch (view.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.btn_query:
				query(editContent.getText().toString());
				break;
			case R.id.img_close:
				tvDrugDesc.setText("");
				layoutTip.setVisibility(View.GONE);
				break;
			case R.id.haolingju_logo:
				String getUrl = "http://www.whhaolinju.com";
				Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(getUrl);
                intent.setData(content_url);
				System.out.println(getUrl);
				skipActivity(this,intent);
				break;
			default:
				break;
		}
	}

	private void query(final String content) {
		final Dialog dialog = CustomProgressDialog.createDialog(this)
				.setMessage(R.string.loading);
		dialog.show();
		StringRequest stringRequest = new StringRequest(Method.POST,
				Contants.api_url, new Listener<String>() {

					@Override
					public void onResponse(String response) {
						KJLoger.debug(response);
						dialog.dismiss();
						QueryResultResponse reseResponse = new Gson().fromJson(
								response, QueryResultResponse.class);
						if (reseResponse.flag.equals(BaseResponse.flag_success)) {
							List<QueryResult> list = new ArrayList<QueryResult>();
							list.addAll(reseResponse.array);
							if (list != null && list.size() > 0) {
								QueryResultAdapter adapter = new QueryResultAdapter(
										MedicineQueryActivity.this, list);
								resultList.setAdapter(adapter);
								layoutQueryType.setVisibility(View.GONE);
								resultList.setVisibility(View.VISIBLE);
								nodata.setVisibility(View.GONE);
							} else {
								resultList.setVisibility(View.GONE);
								nodata.setVisibility(View.VISIBLE);
							}
						} else {
							resultList.setVisibility(View.GONE);
							nodata.setVisibility(View.VISIBLE);
						}
						layoutContent.setVisibility(View.VISIBLE);
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						dialog.dismiss();
						resultList.setVisibility(View.GONE);
						nodata.setVisibility(View.VISIBLE);
						layoutContent.setVisibility(View.VISIBLE);
						if (SystemTool.checkNet(MedicineQueryActivity.this)) {

						} else {
							ViewInject.toast(getString(R.string.net_error));
						}
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				QueryRequest queryRequest = new QueryRequest();
				queryRequest.type = Contants.ApiKey.getUsageList;
				queryRequest.loginid = PreferenceUtil.readString(
						MedicineQueryActivity.this, Contants.SP.login_id);
				queryRequest.cardnum = PreferenceUtil.readString(
						MedicineQueryActivity.this, Contants.SP.cardnum, "");
				queryRequest.content = content;
				String requestJson = new Gson().toJson(queryRequest);
				Map<String, String> map = new HashMap<String, String>();
				map.put(HttpUtil.PARAMS_KEY, requestJson);
				return map;
			}

			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				// TODO Auto-generated method stub
				String str = null;
				try {
					str = new String(response.data, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return Response.success(str,
						HttpHeaderParser.parseCacheHeaders(response));
			}
		};

		mRequestQueue.add(stringRequest);

	}

	public void queryDetail(String id) {
		BaseRequest baseResponse = new BaseRequest();
		baseResponse.type = Contants.ApiKey.getUsageDetail;
		baseResponse.id = id;
		final Dialog dialog = CustomProgressDialog.createDialog(this)
				.setMessage(R.string.loading);
		dialog.show();
		HttpUtil.post(baseResponse, new HttpCallBack() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				KJLoger.debug(t.toString());
				ResultDetailResponse response = new Gson().fromJson(t,
						ResultDetailResponse.class);
				if (response.flag.equals(BaseResponse.flag_success)) {
					String text = "使用说明：" + response.sysm + "\n" + "功能主治："
							+ response.gnzz + "\n" + "不良反应:" + response.blfy
							+ "\n" + "包装：" + response.bz + "\n" + "有效期："
							+ response.yxq;
					tvDrugDesc.setText(text);
				} else {
					tvDrugDesc.setText("暂未录入");
				}
				layoutTip.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				if (SystemTool.checkNet(MedicineQueryActivity.this)) {
					tvDrugDesc.setText("暂未录入");
					layoutTip.setVisibility(View.VISIBLE);
				} else {
					ViewInject.toast(getString(R.string.net_error));
				}
			}

			@Override
			public void onFinish() {
				super.onFinish();
				dialog.dismiss();
			}
		},MedicineQueryActivity.this);
	}

}
